"""
@author: Sergiy Tsymbalyuk
"""

from pylons import url
from pylons.i18n import lazy_ugettext as _

from sqlalchemy import desc

from babel.dates import format_date

from webhelpers.html import literal
from webhelpers.html.tags import link_to
from webhelpers.html.builder import HTML

from chowa.lib.site.navigation import url_outside

from catalogue.lib.base import Session
from catalogue.model.catalog import Document


class HomepageDocuments(object):
    def __init__(self, options={}):
        self.options = options
    
    def render(self):
        query = Session.query(Document).limit(8)
        Session.close()
        tmpl = HTML.span('%s %s %s', style='color:#659A71;') \
            + HTML.span(' %s %s', style='color:#9A7165;') \
            + HTML.span(' "%s"', style='font-weight:normal;')
        doc_text = lambda doc: literal(tmpl) % (unicode(doc.type or _('Unknown')),
                                                doc.institution or '',
                                                _('#').__unicode__() + doc.number if doc.type and doc.type.has_number else '',
                                                _('since'),
                                                format_date(doc.approved, format='long'),
                                                doc.title)
        doc_url = lambda doc: url_outside('catalogue',
                                          controller='document',
                                          action='view',
                                          id=doc.id)
        documents = [link_to(doc_text(document), doc_url(document), class_='homepage-block-link')
                     for document in query]
        
        trs = literal('')
        for document in documents:
            trs += HTML.tr(HTML.td(document, style='padding:8px;'))
        html = HTML.table(trs)
        return html
